<template>
  <u-popup v-model="showPopup" mode="center" border-radius="20" width="90%" height="80%" closeable="true" @close="cancelGift(false)">
    <view class="gift-selection-container">
      <u-toast ref="uToast" />
      <!-- 差额显示区域 -->
      <view class="balance-card" :class="balanceAmount >= 0 ? 'balance-positive' : 'balance-negative'">
        <view class="balance-content flex">
          <view class="balance-label">
            <text class="balance-icon">{{ balanceAmount >= 0 ? '💰' : '⚠️' }}</text>
            <text>可带赠品金额</text>
          </view>
          <view class="balance-amount">
            <text class="currency-symbol">¥</text>
            <text class="amount-value">{{ formatAmount(balanceAmount) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 赠品列表 -->
      <scroll-view class="gift-list" scroll-y="true" enable-back-to-top="true">
        <view 
          class="gift-item" 
          v-for="(item, index) in giftList" 
          :key="index"
        >
          <!-- 辅助信息：第一行显示 item.name -->
          <view class="item-name-row" v-if="item.name">{{ item.name }}</view>
          <view class="product-info-row flex align-center">
              <!-- 复选框 -->
              <view class="checkbox-wrapper" @click="toggleSelect(item)">
                <view class="checkbox" :class="{ 'checked': item.selected }">
                  <text class="checkmark" v-if="item.selected">✓</text>
                </view>
              </view>

              <!-- 商品图片 -->
              <view class="product-image-wrapper">
                <image
                  class="product-image"
                  :src="getImageUrl(item)"
                  mode="aspectFill"
                  @error="onImageError"
                />
              </view>

              <!-- 商品信息 -->
              <view class="product-info">
                <view class="product-name">{{ item.basInv ? item.basInv.cinvname : item.name }}</view>
                <view class="product-details">
                  <view class="detail-row">
                    <text class="detail-label"></text>
                    <text class="quantity-text">x {{ item.syQty || '' }} {{ item.basInv && item.basInv.csacomunitname ? '/ '+ item.basInv.csacomunitname : '' }}</text>
                  </view>
                  <view class="detail-row">
                    <text class="detail-label">类型：赠品</text>
                  </view>
                </view>
              </view>
          </view>

          <!-- 数量选择器 :max="item.syQty || 99999"-->
          <view class="quantity-selector">
            <u-number-box 
              v-model="item.quantity" 
              :min="0" 
              :max="Math.min(item.syQty || 99999, calculateMaxQuantityByAmount(item))"
              input-width="70"
              input-height="50"
              @minus="onMinusClick(item, $event)"
              @plus="onPlusClick(item, $event , index)"
            />
          </view>
        </view>
      </scroll-view>

      <!-- 底部按钮 -->
      <view class="bottom-buttons">
        <view class="button cancel-btn" @click="cancelGift(true)">
          取消赠品
        </view>
        <view class="button confirm-btn" @click="confirmGift">
          确定带赠品
        </view>
      </view>

      <!-- 错误提示弹窗 -->
      <u-modal 
        v-model="showErrorModal" 
        :show-cancel-button="false"
        confirm-text="确定"
        @confirm="showErrorModal = false"
      >
        <view class="error-modal-content">
          <view class="error-icon">✕</view>
          <view class="error-title">所带赠品金额超过本次使用账户余额</view>
          <view class="error-subtitle">无法再继续添加赠品</view>
        </view>
      </u-modal>
    </view>
  </u-popup>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name: 'GiftSelection',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    cusCode: {
      type: String,
      default: ''
    },
    payMoney: {
      type: Number,
      default: 0
    }
  },
  computed: {
    ...mapState(['vuex_config', 'vuex_basCus']),
    // 代理 show prop，避免直接修改 prop
    showPopup: {
      get() {
        return this.show;
      },
      set(value) {
        this.$emit('update:show', value);
      }
    },
    balanceAmount() {
      const selectedGifts = this.giftList.filter(item => item.selected && item.quantity > 0);
      
      // 这里可以添加金额验证逻辑
      const totalGiftAmount = this.calculateTotalGiftAmount(selectedGifts);
      return this.payMoney - totalGiftAmount;
    }
  },
  data() {
    return {
      giftList: [],
      baseUrl: '',
      showErrorModal: false
    }
  },
  watch: {
    show(newVal) {
      if (newVal && this.cusCode) {
        this.loadGiftData(this.cusCode);
      }
    },
    cusCode(newVal) {
      if (newVal && this.show) {
        this.loadGiftData(newVal);
      }
    }
  },
  mounted() {
    this.baseUrl = this.vuex_config ? this.vuex_config.baseUrl : '';
  },
  methods: {
        // 计算基于金额限制的最大数量（考虑已选赠品占用的金额）
    calculateMaxQuantityByAmount(item) {
      const price = parseFloat(item.price || 0);
      if (!price || price <= 0) return item.syQty || 0;

      // 已选其他赠品总金额（排除当前 item）
      const otherSelectedAmount = this.getSelectedTotalAmount(item);

      // 剩余额度 = 支付金额 - 已选其他赠品金额
      const remainingBudget = Math.max(0, this.payMoney - otherSelectedAmount);

      // 在不超支的情况下，当前 item 可选的最大数量（绝对数量）
      const maxByAmount = Math.ceil(remainingBudget / price);
      return maxByAmount;
    },

    // 已选赠品总金额（可排除某个指定 item）
    getSelectedTotalAmount(excludeItem = null) {
      return this.giftList.reduce((sum, gift) => {
        if (excludeItem && gift === excludeItem) return sum;
        if (gift.selected && gift.quantity > 0) {
          const p = parseFloat(gift.price || 0);
          if (p > 0) return sum + (p * gift.quantity);
        }
        return sum;
      }, 0);
    },
    // 加载赠品数据
    loadGiftData(cusCode) {
      this.$u.api.shop.shopGiftListData({ cusCode })
        .then(res => {
          if (res.list && res.list.length > 0) {
            // 过滤掉syQty 为 0 的赠品
            this.giftList = res.list.filter(item => item.syQty > 0).map(item => ({
              ...item,
              selected: false,
              quantity: 1
            }));
            this.baseUrl = this.vuex_config ? this.vuex_config.baseUrl : '';
          }
        })
        .catch(error => {
          console.error('获取赠品数据失败:', error);
          uni.showToast({
            title: '获取赠品数据失败',
            icon: 'none'
          });
        });
    },
    // 验证赠品金额是否超过支付金额
    validateGiftAmount() {
      const selectedGifts = this.giftList.filter(item => item.selected && item.quantity > 0);
      const totalGiftAmount = this.calculateTotalGiftAmount(selectedGifts);
      console.log('totalGiftAmount:', totalGiftAmount, this.payMoney);

      if (totalGiftAmount > this.payMoney) {
        // 将所有非选中的赠品数量设置为0
        this.giftList.forEach(item => {
          if (!item.selected) {
            item.quantity = 0;
          }
        });

        this.showMessage(`赠品金额 ${totalGiftAmount} 超过账户余额 ${this.payMoney}\n可带赠品金额：${this.balanceAmount}`);
        return false;
      }
      return true;
    },
    // 切换选择状态
    toggleSelect(item) {
      const originalSelected = item.selected;
      item.selected = !item.selected;
      if (!item.selected) {
        item.quantity = 1; // 取消选择时重置数量
      } else {
        console.log('validateGiftAmount:', this.validateGiftAmount());
        // 选择时验证金额
        if (!this.validateGiftAmount()) {
          // 如果验证失败，恢复原来的状态
          item.selected = originalSelected;
          return;
        }
      }
    },

    // 数量变化
    onQuantityChange(item, event) {
     const newQuantity = event.value;
      
      // 更新选择状态
      if (newQuantity > 0 && !item.selected) {
        item.selected = true;
      } else if (newQuantity === 0) {
        item.selected = false;
      }
      
      // 验证金额
      // 先保存当前状态，以便验证失败时恢复
      const currentState = {
        quantity: item.quantity,
        selected: item.selected
      };
      
      console.log('验证前:', currentState);
      // 设置新状态用于验证
      item.quantity = newQuantity;
      
      // 验证金额
      if (!this.validateGiftAmount()) {
        // 如果验证失败，恢复原来的状态
        item.quantity = currentState.quantity;
        item.selected = currentState.selected;
        return;
      }

    },

    // 获取图片URL
    getImageUrl(item) {
      if (item.basInv && item.basInv.picUrl) {
        if (item.basInv.picUrl.startsWith('http')) {
          return item.basInv.picUrl;
        }
        return this.baseUrl + item.basInv.picUrl;
      }
      return '/static/image/commodity.png';
    },

    // 图片加载失败
    onImageError() {
      console.log('图片加载失败');
    },

    // 取消赠品
    cancelGift(Boolean) {
      this.$emit('cancel', Boolean);
    },

    // 确定带赠品
    confirmGift() {
      const selectedGifts = this.giftList.filter(item => item.selected && item.quantity > 0);
      
      // 这里可以添加金额验证逻辑
      const totalGiftAmount = this.calculateTotalGiftAmount(selectedGifts);

      console.log('totalGiftAmount:', totalGiftAmount, this.payMoney);

      if (totalGiftAmount > this.payMoney) {
        // this.showErrorModal = true;
        this.showMessage(`赠品金额 ${totalGiftAmount} 超过账户余额 ${this.payMoney}\n可带赠品金额：${this.balanceAmount}`);
        return;
      }
      this.$emit('confirm', selectedGifts);
    },

    // 计算赠品总金额
    calculateTotalGiftAmount(gifts) {
      return gifts.reduce((total, gift) => {
        const price = parseFloat(gift.price || 0);
        console.log('price:', price, gift.quantity, total);
        return total + (price * gift.quantity);
      }, 0);
    },

    // 减少数量点击
    onMinusClick(item, event) {
      // 减少数量时直接更新
      const newQuantity = item.quantity - 1;
      item.quantity = newQuantity;
      
      // 更新选择状态
      if (newQuantity > 0 && !item.selected) {
        item.selected = true;
      } else if (newQuantity === 0) {
        item.selected = false;
      }
    },

    // 增加数量点击
    onPlusClick(item, event, index) {
      console.log('增加数量点击:', item, event, index);
      // 增加数量时需要验证
      const newQuantity = item.quantity;
      
      // 保存当前状态用于验证失败时恢复
      const previousState = {
        quantity: item.quantity - 1 ,
        selected: item.selected
      };
      console.log('验证前:', previousState, !this.validateGiftAmount(), newQuantity);
      // 更新选择状态
      if (newQuantity > 0 && !item.selected) {
        item.selected = true;
      } else if (newQuantity === 0) {
        item.selected = false;
      }
      
      // 临时设置新数量用于验证
      item.quantity = newQuantity;
      
      // 验证金额
      if (!this.validateGiftAmount()) {
        // 如果验证失败，恢复原来的数量和选择状态
        // this.$set(item, 'quantity', previousState.quantity);
        // this.$set(item, 'selected', previousState.selected);
        this.$set(this.giftList, index, {
          ...this.giftList[index],
          quantity: previousState.quantity,
          selected: previousState.selected
        });
        console.log('验证失败:', this.giftList[index], previousState);
        return;
      }
      
      // 验证通过，保持新状态
    },

    // 格式化金额显示
    formatAmount(amount) {
      if (typeof amount !== 'number') {
        return '0.00';
      }
      // return Math.abs(amount).toFixed(2);
      return amount.toFixed(2);
    },

    // 统一长文案提示：长文用 u-toast 顶部展示，短文用 $u.toast
    showMessage(message) {
      const text = String(message || '');
      if (this.$refs.uToast && this.$refs.uToast.show) {
        this.$refs.uToast.show({
          title: text,
          type: 'default',
          position: 'center',
          duration: 2000,
          icon: false
        })
      } else {
        // 回退
        this.$u.toast(text);
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.gift-selection-container {
  background-color: #f5f5f5;
  height: 100%;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
}

// 差额卡片样式
.balance-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 24rpx;
  padding: 11rpx 36rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.25);
  transition: all 0.3s ease;
  
  &.balance-negative {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
    box-shadow: 0 8rpx 24rpx rgba(255, 107, 107, 0.3);
  }
  
  .balance-content {
    .balance-label {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      margin-right: 32rpx;
      
      .balance-icon {
        font-size: 36rpx;
        margin-right: 12rpx;
      }
      
      text {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.9);
        font-weight: 500;
      }
    }
    
    .balance-amount {
      display: flex;
      align-items: baseline;
      margin-bottom: 12rpx;
      
      .currency-symbol {
        font-size: 32rpx;
        color: #fff;
        font-weight: 600;
        margin-right: 8rpx;
      }
      
      .amount-value {
        font-size: 56rpx;
        color: #fff;
        font-weight: bold;
        line-height: 1.2;
      }
    }
    
    .balance-tip {
      background-color: rgba(255, 255, 255, 0.2);
      padding: 10rpx 20rpx;
      border-radius: 16rpx;
      display: inline-block;
      
      text {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.95);
        font-weight: 500;
      }
    }
  }
}

.gift-list {
  flex: 1;
  overflow-y: auto;
  
  .gift-item {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    flex-wrap: wrap; // 允许第一行独占显示
    position: relative;
    
    .item-name-row {
      flex-basis: 100%;
      width: 100%;
      margin-bottom: 12rpx;
      padding: 10rpx 16rpx;
      font-size: 26rpx;
      color: #666;
      background-color: #f9fafb;
      border: 1rpx solid #eee;
      border-radius: 18rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .checkbox-wrapper {
      margin-right: 20rpx;

      .checkbox {
        width: 40rpx;
        height: 40rpx;
        border: 2rpx solid #ddd;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #fff;

        &.checked {
          background-color: #007aff;
          border-color: #007aff;

          .checkmark {
            color: #fff;
            font-size: 24rpx;
            font-weight: bold;
          }
        }
      }
    }

    .product-image-wrapper {
      margin-right: 20rpx;

      .product-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 12rpx;
        background-color: #f5f5f5;
      }
    }

    .product-info {
      flex: 1;
      margin-right: 20rpx;

      .product-name {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
        line-height: 1.4;
        width: 385rpx;
      }

      .product-details {
        .detail-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8rpx;

          .detail-label {
            font-size: 28rpx;
            color: #666;
          }

          .quantity-text {
            font-size: 28rpx;
            color: #666;
          }
        }
      }
    }

    .quantity-selector {
      min-width: 120rpx;
      position: absolute;
      right: 30rpx;
      bottom: 14rpx;
    }
  }
}

.bottom-buttons {
  background-color: #fff;
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  margin-top: auto;

  .button {
    flex: 1;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: bold;

    &.cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }

    &.confirm-btn {
      background-color: #ff6b35;
      color: #fff;
    }
  }
}

.error-modal-content {
  text-align: center;
  padding: 40rpx;

  .error-icon {
    width: 80rpx;
    height: 80rpx;
    background-color: #ff4757;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40rpx;
    font-weight: bold;
    margin: 0 auto 30rpx;
  }

  .error-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .error-subtitle {
    font-size: 28rpx;
    color: #666;
  }
}
</style>
